﻿using System;
using System.IO;
using System.Reflection;
using System.Web.Mvc;

namespace SmallBusinessKit.Controllers
{
    [HandleError]
    public class BaseController : Controller
    {
        #region Properties

        #endregion

        #region Methods

        protected BaseController()
        {
            ViewBag.Version   = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            ViewBag.BuildDate = RetrieveLinkerTimestamp();
        }

        private DateTime RetrieveLinkerTimestamp()
        {
            const int cPeHeaderOffset        = 60;
            const int cLinkerTimestampOffset = 8;
            var filePath                     = Assembly.GetCallingAssembly().Location;
            var byteArray                    = new byte[2048];

            using (var s = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                s.Read(byteArray, 0, 2048);
            }

            var i  = BitConverter.ToInt32(byteArray, cPeHeaderOffset);
            var buildSecondsSince1970 = BitConverter.ToInt32(byteArray, i + cLinkerTimestampOffset);
            var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(buildSecondsSince1970).ToLocalTime();

            return dt;
        }

        #endregion
    }
}
